package com.taotao.portal.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import Utils.CookieUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.pojo.TbUser;
import com.taotao.portal.httpclientService.HttpClientService;
import com.taotao.portal.service.ItemService;

public class LoginInterceptor implements HandlerInterceptor {

	private static final String COOKIE_NAME = "_PHF_TOKEN";

	private static final ObjectMapper MAPPER = new ObjectMapper();
	
	private static final Logger l = LoggerFactory.getLogger(LoginInterceptor.class);

	@Autowired
	private HttpClientService httpService;

	@Autowired
	private ItemService service;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String token = CookieUtils.getCookieValue(request, COOKIE_NAME);

		/**
		 * 查询cookie是否存在用户信息
		 */
		if (StringUtils.isEmpty(token)) {

			String requestURI = request.getHeader("referer");
			CookieUtils.setCookie(request, response, "returnUrl", requestURI);
			response.sendRedirect(service.SSO_BASE_URL + "/login.html?"
					+ "returnUrl=" + requestURI);
			return false;
		}

		/**
		 * 查询缓存是否存在用户信息
		 */
		String url = service.SSO_BASE_URL + "/sso/user/" + token;
		TbUser user = null;
		try {
			String data = httpService.doGet(url);
			user = MAPPER.readValue(data, TbUser.class);
		} catch (Exception e) {

		}
        if(l.isDebugEnabled())
        	l.debug("查询到用户信息" + user);
		if (null == user) {// 如果用户未登录，转到登录页面
			String requestURI = request.getHeader("referer");
			CookieUtils.setCookie(request, response, "returnUrl", requestURI);
			response.sendRedirect(service.SSO_BASE_URL + "/login.html?"
					+ "returnUrl=" + requestURI);
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}
}
